package com.xingchi.tornado.security.handler;

import com.xingchi.tornado.security.config.SecurityProperties;
import com.xingchi.tornado.security.constants.SecurityConstants;
import com.xingchi.tornado.security.model.IUser;
import com.xingchi.tornado.security.model.LoginData;
import lombok.RequiredArgsConstructor;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 默认session属性填充服务
 *
 * @author xingchi
 * @date 2025/9/17 22:38
 */
@Service
@RequiredArgsConstructor
public class DefaultSessionAttributeService implements SessionAttributeService {

    private final SecurityProperties properties;

    @Override
    public void fillSessionAttribute(HttpSession session, LoginData<? extends IUser> loginData) {
        session.setAttribute(SecurityConstants.LOGIN_DATA, loginData);
        session.setAttribute(SecurityConstants.USER_ID, loginData.getUserId());
        session.setAttribute(SecurityConstants.SESSION_ID, loginData.getSessionId());
        session.setAttribute(SecurityConstants.LOGIN_SOURCE, loginData.getLoginSource());
        session.setAttribute(SecurityConstants.LOGIN_TYPE, loginData.getLoginType());
        session.setAttribute(SecurityConstants.USER_AGENT, loginData.getUserAgent());
        session.setAttribute(SecurityConstants.LOGIN_IP, loginData.getIp());
        session.setAttribute(SecurityConstants.LOGIN_TIME, LocalDateTime.now());
        session.setAttribute(SecurityConstants.ROLE_CODE_LIST, loginData.getRoleCodeList());
        session.setAttribute(SecurityConstants.PERMISSION_CODE_LIST, loginData.getPermissionCodeList());
        session.setMaxInactiveInterval(properties.getExpiresIn());

        session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, String.valueOf(loginData.getUserId()));
    }

}
